<script>
import request from '@/utils/request'  // 确保你有引入request工具

export default {
  name: "Test",
  data() {
    return {
      uid: 101, // 用户ID，这里可以根据实际需求设置
      imageUrl: ''
    }
  },
  methods: {
    // 处理文件上传
    async handleAvatarUpload(event) {
      const file = event.target.files[0]
      if (!file) return

      const formData = new FormData()
      formData.append('uid', this.uid)
      formData.append('file', file)

      try {
        const res = await request({
          url: '/User/UserAvatar/update',
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (res.code === "200") {
          this.$message.success('头像上传成功')
          // 可以在这里更新预览图
          this.imageUrl = URL.createObjectURL(file)
        } else {
          this.$message.error(res.msg || '上传失败')
        }
      } catch (error) {
        console.error('上传出错：', error)
        this.$message.error('上传失败')
      }
    }
  }
}
</script>

<template>
  <div class="testPage">
    <div class="Avatar-testApi">
      <!-- 头像预览 -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar-preview" />
      
      <!-- 上传按钮 -->
      <div class="upload-container">
        <input 
          type="file" 
          accept="image/*" 
          @change="handleAvatarUpload"
          class="file-input"
        >
        <button class="upload-btn">选择头像</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.Avatar-testApi {
  padding: 20px;
  text-align: center;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 20px;
  object-fit: cover;
}

.upload-container {
  position: relative;
  display: inline-block;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.upload-btn {
  padding: 8px 16px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-btn:hover {
  background-color: #66b1ff;
}
</style>